#include "functions.h"

void initialize_center_sigma(){
  int i;

  center = ( double * ) malloc( sizeof( double ) * number_of_dimensions );
  sigma = ( double * ) malloc( sizeof( double ) * number_of_dimensions );

  for( i=0; i<number_of_dimensions; i++ ){
    //center[ i ] = ( upper_limit + lower_limit ) / 2;
    center[ i ] = individuals[ 0 ].design_variables[ i ];
  }

  for( i=0; i<number_of_dimensions; i++ ){
    //    sigma[ i ] = sqrt( calc_elites_var( i ) );
    sigma[ i ] = fabs( upper_limit - lower_limit ) / 2 ;
  }

}

double calc_elites_var( int d ){
  int i;
  double average = 0.0;
  double sum = 0.0;

  for( i=0; i<number_of_elites; i++ ){
    average += individuals[ i ].design_variables[ d ];
  }

  average = average / number_of_elites;
  
  for( i=0; i<number_of_elites; i++ ){
    sum += pow( ( individuals[ i ].design_variables[ d ] - average ), 2 );
  }

  return sum / number_of_elites;

}

void destory_center_sigma(){

  free( center );
  free( sigma );

}


void create_p_model(){
  int i;
  double *pre_center, *pre_sigma;

  pre_center = ( double * ) malloc( sizeof( double ) * number_of_dimensions );
  pre_sigma = ( double * ) malloc( sizeof( double ) * number_of_dimensions );

  for( i=0; i<number_of_dimensions; i++ )
    {
      pre_center[ i ] = center[ i ];
      pre_sigma[ i ] = sigma[ i ];
    }

  calc_center( center );
   
   /*
   printf( "C2:" );
   for( i=0; i<number_of_dimensions; i++ )
     printf( "%f\t", center[i] );
   printf( "\n" );
   */

  for( i=0; i<number_of_dimensions; i++ )
    center[ i ] = ( 1.0 - alpha ) * pre_center[ i ] + alpha * center[ i ];
    
   //   printf( "A2:" );
   for( i=0; i<number_of_dimensions; i++ ){
     sigma[ i ] = sqrt( calc_elites_var( i ) );
     //     printf( "%f\t", sigma[i] );
     sigma[ i ] = ( 1.0 - alpha ) * pre_sigma[ i ] + alpha * sigma[ i ];
     //          sigma[i]=0.02;
   }
   //   printf( "\n" );
   

   free( pre_center );
   free( pre_sigma );

}

void calc_center(){
  int i;

  for( i=0; i<number_of_dimensions; i++ )
    {
      //center[ i ] = individuals[ 0 ].design_variables[ i ] ;
      center[ i ] = individuals[ 0 ].design_variables[ i ] + 
      	individuals[ 1 ].design_variables[ i ] - individuals[ population_size - 1 ].design_variables[ i ];
    }

}
